<template>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
      <el-breadcrumb-item v-if="addOrEdit=='add'">写文章</el-breadcrumb-item>
      <el-breadcrumb-item v-if="addOrEdit=='edit'">修改文章</el-breadcrumb-item>

    </el-breadcrumb>
    <h2 v-if="addOrEdit=='add'">写文章</h2>
    <h2 v-if="addOrEdit=='edit'">修改文章</h2>

    <el-row :gutter="20">
      <el-form :label-position="labelPosition" label-width="80px" :model="newsForm" :rules="newsFormRules" ref="newsFormRef">
        <el-col :span="16">
          <el-form-item label="标题" prop="title">
            <el-input
              type="text"
              placeholder="请输入内容"
              v-model="newsForm.title"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="newsForm.content" type="textarea" rows="13"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文章封面" prop="cover">
            <input type="file" @change="getCoverUrl" accept="image/png, image/gif, image/jpeg" />
          </el-form-item>
          <div id="imageBox" v-html="URL">
            <!-- <img src="URL" /> -->
          </div>
          <el-form-item label="所属分类" style="width=100%" prop="class">
            <el-select v-model="newsForm.classId" placeholder="请选择分类">
              <el-option
                :label="item.name"
                :value="item.classId"
                v-for="item in classList"
                :key="item.classId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间" prop="date">
             <el-date-picker
                v-model="newsForm.date"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态" style="width=100%" prop="state">
            <el-select v-model="newsForm.state" placeholder="请选择分类">
              <el-option label="草稿" value="0"></el-option>
              <el-option label="发布" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" round @click="editNews" v-if="addOrEdit=='edit'">修改</el-button>
          <el-button type="primary" round @click="addNews" v-if="addOrEdit=='add'">添加</el-button>

        </el-col>
      </el-form>
    </el-row>
  </el-card>
</template>
<script>
export default {
  // eslint-disable-next-line space-before-function-paren
  data() {
    return {

      // 新增还是修改的控制器
      addOrEdit: '',
      // 表单的对齐方式
      labelPosition: 'top',
      // 图片的路径
      URL: '',
      // 分类列表
      classList: [],
      newsForm: {
        title: '',
        content: '',
        cover: '',
        classId: '',
        date: '',
        state: '',
        email: ''
      },
      newsFormRules: {

        content: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '该项不能为空' }
        ],
        classId: [
          { required: true, message: '该项不能为空' }
        ],
        date: [
          { required: true, message: '该项不能为空' }
        ],
        state: [
          { required: true, message: '该项不能为空' }
        ]
      }
      // 验证规则
    }
  },
  // eslint-disable-next-line space-before-function-paren
  created() {
    // 获取分类列表
    this.getClassList()
    this.setNewsFormEmail()
    this.checkAddOrEdit()
    this.getNewsInfo()
  },

  methods: {
    setNewsFormEmail () {
      this.newsForm.email = window.sessionStorage.getItem('token')
    },
    async getClassList () {
      const { data: res } = await this.$http.get('api/class')
      this.classList = res.Table
    },
    // 当选择了文件后，上传到服务器获取路径
    async getCoverUrl (e) {
      const file = e.target.files[0]
      const param = new FormData() // 创建form对象
      param.append('file', file) // 通过append向form对象添加数据
      // console.log(param.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      // 添加请求头
      const { data: res } = await this.$http.post('api/upload', param, config)
      // eslint-disable-next-line no-const-assign
      const url = `<img src="http://localhost:63135/image/${res}" style="height:100%;"/>`
      this.URL = url
      console.log(url)
      this.newsForm.cover = res[0]
    },
    // 当编辑模式时将图片放到预览区
    setCover () {
      if (this.addOrEdit === 'edit') {
        const url = `<img src="http://localhost:63135/image/${this.newsForm.cover}" style="height:100%;"/>`
        this.URL = url
      }
    },
    async addNews () {
      // 如果没有通过验证规则
      this.$refs.newsFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 通过了验证规则
        console.log(this.newsForm)

        var params = new URLSearchParams()
        params.append('title', this.newsForm.title)
        params.append('content', this.newsForm.content)
        params.append('cover', this.newsForm.cover)
        params.append('classId', this.newsForm.classId)
        params.append('date', this.newsForm.date)
        params.append('state', this.newsForm.state)
        params.append('email', this.newsForm.email)

        const { data: res } = await this.$http({
          method: 'post',
          url: 'api/news',
          data: params,
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        if (res.status !== 200) return this.$message.error('创建文章失败')
        this.$message.success('创建文章成功')
        this.$refs.newsFormRef.resetFields()
        this.URL = ''
      })
    },

    // 判断是新增还是修改
    checkAddOrEdit () {
      if (this.$route.query.newsId) {
        this.addOrEdit = 'edit'
      } else {
        this.addOrEdit = 'add'
      }
    },
    // 若是修改，获取newsId的信息
    async getNewsInfo () {
      if (this.addOrEdit === 'edit') {
        const { data: res } = await this.$http.get('/api/news/' + this.$route.query.newsId)
        this.newsForm = res.Table[0]
        console.log(this.newsForm)
        // 设置图片预览
        this.setCover()
      }
    },
    // 修改文章
    editNews () {
      // 如果没有通过验证规则
      this.$refs.newsFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        // 通过了验证规则
        console.log(this.newsForm)

        var params = new URLSearchParams()
        params.append('newsId', this.$route.query.newsId)
        params.append('title', this.newsForm.title)
        params.append('content', this.newsForm.content)
        params.append('cover', this.newsForm.cover)
        params.append('classId', this.newsForm.classId)
        params.append('date', this.newsForm.date)
        params.append('state', this.newsForm.state)
        params.append('email', this.newsForm.email)

        const { data: res } = await this.$http({
          method: 'post',
          url: 'api/update',
          data: params,
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        console.log(res)

        if (res.status !== 200) return this.$message.error('修改用户失败')
        this.$message.success('修改用户成功')
        this.$router.push('/home/news')
      })
    }
  },
  watch: {
    // 同一个页面，当从编辑页面跳到增加页面时，重新刷新页面
    $route (to, from) { // 监听路由是否变化
      this.$router.go(0)
    }
  }
}
</script>
<style lang="less" scoped>
.el-select {
  width: 100%;
}
#imageBox {
  width: 177px;
  height: 100px;
  border: 1px solid #000;

  // background-image: url();
}
.el-form-item {
    margin-bottom: 0px;
}
.el-form-item__label
{
  padding: 0px !important;
}
</style>
